package com.zbkj.crmeb.chant.controller;


import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.zbkj.crmeb.chant.model.ReserveMoneyDetail;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageInfo;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.category.request.CategoryRequest;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.category.vo.CategoryTreeVo;
import com.zbkj.crmeb.chant.dto.ChannelMerchantDTO;
import com.zbkj.crmeb.chant.dto.ChannelMerchantSupplierDTO;
import com.zbkj.crmeb.chant.request.AccountCenterRequest;
import com.zbkj.crmeb.chant.request.MerchantListRequest;
import com.zbkj.crmeb.chant.request.OfflineCompensatoryRequest;
import com.zbkj.crmeb.chant.request.OfflineRechargeRequest;
import com.zbkj.crmeb.chant.request.SettlementSupplierRequest;
import com.zbkj.crmeb.chant.response.AccountCenterResponse;
import com.zbkj.crmeb.chant.response.SupplierAccountCenterResponse;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.vo.ChannelMerchantVO;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.request.AddSupplierRequest;
import com.zbkj.crmeb.store.service.SupplierService;

/**
 * 渠道商户
 */
@Slf4j
@RestController("ChannelMerchantController")
@RequestMapping("api/chant/channel-merchant")
@Api(tags = "渠道商户")
public class ChannelMerchantController {

    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SupplierService supplierService;

    /**
     * 渠道商户列表
     * @return
     */
    @ApiOperation(value = "渠道商户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<ChannelMerchantVO>> merchantList(MerchantListRequest request){
    	// 过滤供应商
    	request.setNotChannelType(3);
        PageInfo<ChannelMerchantVO> pageInfo = channelMerchantService.merchantList(request);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 渠道商户列表
     * @return
     */
    @ApiOperation(value = "渠道商户列表")
    @RequestMapping(value = "/listV2", method = RequestMethod.GET)
    public CommonResult<CommonPage<ChannelMerchantVO>> supplierMerchantList(MerchantListRequest request){
    	// 过滤供应商
    	request.setNotChannelType(3);
        PageInfo<ChannelMerchantVO> pageInfo = channelMerchantService.merchantListV2(request, true);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 渠道供应商列表
     * @return
     */
    @ApiOperation(value = "渠道供应商列表")
    @RequestMapping(value = "/supplier/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<ChannelMerchantVO>> merchantSupplierList(MerchantListRequest request){
    	PageInfo<ChannelMerchantVO> pageInfo = channelMerchantService.merchantList(request);
    	return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 根据id获得渠道商户信息
     * @return
     */
    @ApiOperation(value = "根据id获得渠道商户信息")
    @GetMapping(value = "/getMerchantById/{id}")
    public CommonResult<ChannelMerchantVO> getMerchantById(@PathVariable("id") Integer id){
        return CommonResult.success(channelMerchantService.getMerchantById(id));
    }

    /**
     * 添加渠道商户
     */
    @ApiOperation(value = "添加渠道商户")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public CommonResult<String> addMerchant(@RequestBody @Validated ChannelMerchantDTO entity){
        return channelMerchantService.addMerchant(entity);
    }
    
    /**
     * 添加供应商
     */
    @ApiOperation(value = "添加供应商")
    @RequestMapping(value = "/supplier/add", method = RequestMethod.POST)
    public CommonResult<String> addMerchantSupplier(@RequestBody @Validated ChannelMerchantSupplierDTO entity){
    	return channelMerchantService.addMerchantSupplier(entity);
    }

    /**
     * 修改渠道商户
     */
    @ApiOperation(value = "修改渠道商户")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResult<String> updateMerchant(@RequestBody @Validated ChannelMerchantDTO entity){
        return channelMerchantService.updateMerchant(entity);
    }
    
    /**
     * 修改供应商
     */
    @ApiOperation(value = "修改供应商")
    @RequestMapping(value = "/supplier/update", method = RequestMethod.POST)
    public CommonResult<String> updateMerchantSupplier(@RequestBody @Validated ChannelMerchantSupplierDTO entity){
    	return channelMerchantService.updateMerchantSupplier(entity);
    }

    /**
     * 删除渠道商户
     */
    @ApiOperation(value = "删除渠道商户")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public CommonResult<String> deleteMerchant(@PathVariable("id") Integer id){
        if(channelMerchantService.deleteMerchant(id)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "商户线下充值")
    @PostMapping("/recharge/offline")
    public CommonResult<String> offlineRecharge(@RequestBody @Validated OfflineRechargeRequest request, HttpServletRequest httpServletRequest){
        boolean b = channelMerchantAccountService.offlineRecharge(request, CrmebUtil.getClientIp(httpServletRequest));
        return b ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "补偿性充值")
    @PostMapping("/compensatory/offline")
    public CommonResult<String> offlineCompensatory(@RequestBody @Validated OfflineCompensatoryRequest request, HttpServletRequest httpServletRequest){
        boolean b = channelMerchantAccountService.offlineCompensatory(request, CrmebUtil.getClientIp(httpServletRequest));
        return b ? CommonResult.success() : CommonResult.failed();
    }


    @ApiOperation(value = "渠道商户账户中心")
    @GetMapping(value = "/account/center")
    public CommonResult<AccountCenterResponse> accountCenter(@Validated AccountCenterRequest request){
        if(null == request.getMerId()){
            throw new CrmebException("商户id不能为空!");
        }
        return CommonResult.success(channelMerchantAccountService.accountCenter(request));
    }

    @ApiOperation(value = "账户中心查看详情")
    @GetMapping(value = "/account/info/{id}")
    public CommonResult<Object> accountInfo(@PathVariable("id") Integer id){
        return CommonResult.success(channelMerchantAccountService.accountInfo(id,true));
    }

    @ApiOperation(value = "冻结/解冻商户账户")
    @GetMapping(value = "/account/frozen/{id}/{status}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="商户id"),
            @ApiImplicitParam(name="status", value="状态 false解冻 true冻结")
    })
    public CommonResult<String> accountFrozen(@PathVariable("id") Integer id,@PathVariable("status") Boolean status){
        return channelMerchantAccountService.accountFrozen(id,status) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "供应商账户中心")
    @GetMapping(value = "/account/center/supplier/{id}")
    public CommonResult<SupplierAccountCenterResponse> supplierAccountCenter(@PathVariable("id") Integer merId,PageParamRequest pageParamRequest){
        return CommonResult.success(channelMerchantAccountService.supplierAccountCenter(merId,pageParamRequest));
    }

    @ApiOperation(value = "供应商批量结算")
    @PostMapping(value = "/settlement/supplier")
    public CommonResult<Boolean> settlementSupplier(@RequestBody SettlementSupplierRequest request,HttpServletRequest httpServletRequest) {
        return channelMerchantAccountService.settlementSupplier(request,CrmebUtil.getClientIp(httpServletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "获取发货地")
    @GetMapping(value = "/stockArea")
    public CommonResult<List<StockAreaTempEnum>> getStockArea(HttpServletRequest servletRequest){
        return CommonResult.success(StockAreaTempEnum.listEnum());
    }

    @ApiOperation(value = "获取商品推送状态")
    @GetMapping(value = "/productStatus")
    public CommonResult<List<Map<String,String>>> getProductStatus(HttpServletRequest servletRequest){
        return CommonResult.success(PlatPushStatusEnums.listEnum());
    }

    @ApiOperation(value = "查询渠道商分类")
    @GetMapping(value = "/getCategoryByChannel")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="商户id"),
    })
    public CommonResult<List<CategoryTreeVo>> getCategoryByChannel(@RequestParam Integer id, HttpServletRequest servletRequest){
        //渠道商分类是否启用标志字段 enableFlag
        return CommonResult.success(categoryService.getMerListTree(1,1,id));
    }

    @ApiOperation(value = "修改渠道商分类")
    @PostMapping(value = "/updCategoryByChannel")
    public CommonResult<Object> updCategoryByChannel(@RequestBody CategoryRequest categoryRequest, HttpServletRequest servletRequest){
        return channelMerchantService.updCategoryByChannel(categoryRequest) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "渠道商户添加备注")
    @PostMapping(value = "/remarks")
    public CommonResult<Boolean> merAddRemarks(@RequestParam String remarks,@RequestParam Integer merId) {
        return CommonResult.success(channelMerchantService.merAddRemarks(remarks, merId));
    }

    @ApiOperation(value = "供应商备用金调整")
    @PutMapping(value = "/supplier/reserveMoney")
    public CommonResult<Boolean> updateReserveMoney(@ApiParam(value = "需要调整备用金的供应商id") Integer merId,
                                                    @ApiParam(value = "增加：true, 减少: false") Boolean add,
                                                    @ApiParam(value = "调整金额") BigDecimal money) {
        return channelMerchantService.updateReserveMoney(merId, add, money) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "备用金明细")
    @GetMapping(value = "/supplier/reserveMoney")
    public CommonResult<CommonPage<ReserveMoneyDetail>> getDetailList(Integer merId, PageParamRequest request) {
        return CommonResult.success(channelMerchantService.getDetailList(merId, request));
    }


    /**
     * 新增
     */
    @ApiOperation(value = "新增")
    @PostMapping(value = "/addSuppliersName")
    public CommonResult<String> addSuppliersName(@RequestBody @Validated AddSupplierRequest request){
        log.info("save Supplier：{}", JSON.toJSONString(request));
//        Integer merId = getMerId(servletRequest);
//        request.setMerId(merId);

        Supplier supplier = supplierService.lambdaQuery()
                .eq(Supplier::getSuppliersName, request.getSuppliersName())
                .eq(Supplier::getIsDeleted, false)
                .one();

        if(supplier != null) {
            return CommonResult.failed("该供应商名称已存在");
        }
        return supplierService.addSupplier(request) ? CommonResult.success() : CommonResult.failed();
    }

}
